package com.student.education.controller;

import com.student.education.common.CommonPage;
import com.student.education.common.CommonResult;
import com.student.education.entity.Consumption;
import com.student.education.service.ConsumptionService;
import com.student.education.to.ConsumptionCountTo;
import com.student.education.to.ConsumptionQueryTo;
import com.student.education.to.ConsumptionTo;
import com.student.education.util.ExcelUtils;
import com.student.education.vo.ConsumptionVo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 消费信息表(Consumption)表控制层
 *
 * @author makejava
 * @since 2021-10-06 21:56:55
 */
@RestController
@RequestMapping("consumption")
public class ConsumptionController {
    /**
     * 服务对象
     */
    @Resource
    private ConsumptionService consumptionService;

    /**
     * 编辑数据
     *
     * @param consumption 实体
     * @return 编辑结果
     */
    @PostMapping("/query")
    public CommonResult<CommonPage<ConsumptionQueryTo>> query(@RequestBody ConsumptionVo consumption) {
        return CommonResult.success(this.consumptionService.query(consumption));
    }

    @GetMapping("/count")
    public CommonResult<ConsumptionCountTo> count(Integer userId) {
        return CommonResult.success(this.consumptionService.count(userId));
    }
    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.consumptionService.deleteById(id));
    }

    /**
     * Excel导入
     * @param file
     */
    @PostMapping("/upload")
    public CommonResult<String> readExcel(@RequestBody MultipartFile file){
        System.out.println("上传的文件："+file.getOriginalFilename());
        List<ConsumptionTo> list = ExcelUtils.readExcel("", ConsumptionTo.class, file);
        int total = consumptionService.insert(list);
        if (total>0){
            CommonResult.success("导入成功");
        }
        return CommonResult.error("导入失败");
    }
    /**
     * 模板下载
     * @param response
     */
    @GetMapping("/downloadModel")
    public void downloadModel(HttpServletRequest request, HttpServletResponse response){
        List<ConsumptionTo> empList = new ArrayList<>();
        ExcelUtils.writeExcel(request,response, empList, ConsumptionTo.class);
        return;
    }

}

